<?php
class chat extends HttpPhplet {
    var $initTime;
    var $users;
    var $messages; 
     

    function init(&$config)
    {
        $this->initTime = gmdate("D, d M Y H:i:s T");
        $this->users = array();
    }

    function service(&$request, &$response)
    {
        $nick = $request->getParameter("nick");        
        switch ($request->getParameter("action"))
        {
            case 'join':
                if (empty($nick))
                {
                    $response->write("'err1 (empty nickname)'");
                } else if (array_key_exists($nick,$this->users)) {
                
                    $response->write("'err2 (nickname yet used into this room)'");
                } else {
                    $this->users[$nick] = time();
                    $response->write("'joindone'");
                }
            break;
            
            case 'pushmessage':
                $message = $request->getParameter("message");                
                $this->messages[] = array(time(),$nick,$message);
                $response->write("[['".time()."'],['$nick'],['$message']]");            
            break;
            
            
            case 'getupdates':
                  $response->write('[[');   
                            $lastts = $request->getParameter("lastts");
                if (!$lastts)
                    $lastts = $this->users[$nick];            

                foreach ($this->messages as $msg) {
                    if ($msg[0] > $lastts && $msg[1] != $nick )
                    {
                        $response->write("[['".$msg[0]."'],['".$msg[1]."'],['".$msg[2]."']],");                        
                    }
                }
                  $response->write('],[');                   
                   foreach ($this->users as $user=>$time)
                        $response->write("['".$user."'],");                   
                
                $response->write("],['".time()."']]");                                                  
            break;
            
            case 'leave':
                unset ($this->users[$nick]);
            break;
            
            
                        
            case 'dumpusers':
                $response->write('<pre>');
                $response->write(print_r($this->users,true));
                $response->write('</pre>');                
            break;
            
            
            
            
           
        
        }

    }

    function destroy()
    {
    }
}
